﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data;
using DataAccessor.Exceptions;

namespace DataAccessor
{
    /// <summary>
    /// 对IDataAccessor的MS Access实现
    /// </summary>
    public class MSAccess : IDataAccessor
    {
        #region 构造函数
        /// <summary>
        /// 创建指定配置的数据访问实例
        /// </summary>
        /// <param name="databaseName">模块名</param>
        /// <param name="configName">配置名</param>
        public MSAccess(string databaseName, string configName)
            : base(databaseName, configName)
        {
        }

        /// <summary>
        /// 创建指定配置的数据访问实例
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        public MSAccess(string connectionString)
            : base(connectionString)
        {
        }
        #endregion

        /// <summary>
        /// 返回当前DBMS的字符串
        /// </summary>
        public override string DBMS
        {
            get { return "MSAccess"; }
        }

        /// <summary>
        /// 数据库连接锁
        /// </summary>
        private object _connectionLock = new object();
        /// <summary>
        /// 创建数据库连接
        /// </summary>
        protected override DbConnection CreateConnection()
        {
            if (!SingletonConnection)
            {
                return new OleDbConnection(ConnectionString);
            }
            else
            {
                if (Connection == null)
                {
                    lock (_connectionLock)
                    {
                        if (Connection == null)
                        {
                            Connection = new OleDbConnection(ConnectionString);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(Connection.ConnectionString))
                    {
                        Connection.ConnectionString = ConnectionString;
                    }
                }
                return Connection;
            }
        }

        /// <summary>
        /// 创建一个DbCommand的实例
        /// </summary>
        /// <param name="withConnection">是否同时创建连接？</param>
        /// <returns>返回DbCommand的一个实例</returns>
        protected override DbCommand CreateCommand()
        {
            return new OleDbCommand();
        }

        /// <summary>
        /// 创建一个DbCommand的实例
        /// </summary>
        /// <returns>返回DbCommand的一个实例</returns>
        protected override DbDataAdapter CreateAdapter(DbCommand cmd)
        {
            return new OleDbDataAdapter(cmd as OleDbCommand);
        }
    }
}
